<template>
  <view class="container">
    <!-- 字母区域 -->
    <view class="cityLetter">
      <view hover-class="clickLatter" @tap="getLetter('ScrollTop')">*</view>
      <view v-for="(item, index) in latterName" :key="index" hover-class="clickLatter" @tap="getLetter(item)" :style="{ color: letterId === item ? '#4662D9' : '#000' }">
        {{ item }}
      </view>
    </view>

    <view class="autoLocation u_flex">
      <view class="autoAddress">
        <text class="text">当前定位：</text>
        <text @tap="getStorage(locationCityName)">{{ locationCityName ? locationCityName : '--' }}</text>
      </view>

      <view class="relocation u_flex" @click="getLocationAuth">
        <u-icon name="reload" color="#000"></u-icon>
        <text class="ml5">重新定位</text>
      </view>
    </view>

    <scroll-view class="scrollView" scroll-y="true" :scroll-into-view="letterId">
      <!-- 热门城市 -->
      <view class="hotCity" id="ScrollTop">
        <view class="hotCityTitle">
          <text class="text">热门城市</text>
        </view>
        <view class="hotCityList flex">
          <text class="text" @tap="getStorage(item)" v-for="(item, index) in hotCityList" :key="index">{{ item }}</text>
        </view>
      </view>
      <!-- 城市列表 -->
      <view class="cityList">
        <block v-for="(item, index) in cityList" :key="index">
          <view class="letter" :id="item.initial">{{ item.initial }}</view>
          <view class="cityLine">
            <text v-for="(item_city, name_index) in item.list" :key="name_index" @tap="getStorage(item_city.name)">{{ item_city.name }}</text>
          </view>
        </block>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
//https://blog.csdn.net/Tianxiaoxixi/article/details/129126709
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import cityData from '@/utils/city.json'; // 导入JSON文件

const cityList = ref(cityData.city); //引用json城市数据
const hotCityList = ref(['北京', '深圳', '上海', '成都', '广州', '重庆']);
const latterName = ref(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']);
const letterId = ref('');
const cityName = ref('');
const locationCityName = ref('');

onLoad(() => {
  getCityName();
});

//获取定位点
const getLetter = (name) => {
  letterId.value = name;
  // uni.pageScrollTo({
  // 	selector:'#'+name,
  // 	duration:300
  // })
};

//存储城市
const getStorage = (val) => {
  val += val.endsWith('市') ? '' : '市';
  uni.setStorageSync('CityName', val);
  cityName.value = val;
  //跳转返回
  uni.navigateBack({
    url: '/pages/index/index'
  });
};

//获得城市缓存
const getCityName = () => {
  setTimeout(() => {
    let city = uni.getStorageSync('CityName');
    console.log('获取初始城市：', city);
    cityName.value = city;
  }, 500);
  getLocationAuth();
};

//重新定位按钮
const getLocationAuth = () => {
  uni.getSystemInfo({
    success(res) {
      console.log('getSystemInfo: ', res);
      let locationEnabled = res.locationEnabled; //判断手机定位服务是否开启
      let locationAuthorized = res.locationAuthorized; //判断定位服务是否允许微信授权
      if (locationEnabled == false || locationAuthorized == false) {
        //手机定位服务（GPS）未授权
        uni.showModal({
          title: '提示',
          content: '请打开定位服务功能',
          showCancel: false, // 不显示取消按钮
          success: (res) => {
            console.log('showModalres', res);
          }
        });
      } else {
        uni.authorize({
          scope: 'scope.userLocation', //授权的类型为地理位置
          success: (res) => {
            uni.getLocation({
              type: 'gcj02',
              geocode: true,
              isHighAccuracy: true,
              accuracy: 'best', // 精度值为20m
              success: function (res) {
                let lat = res.latitude;
                let lng = res.longitude;
                let key = 'KWJBZ-7GJ6O-X3CW5-SLUT3-IVW7K-MMFV2'; //申请地址：https://lbs.qq.com/dev/console/application/mine   GZHBZ-PITKB-2ZJUT-JQ6PK-XS44K-Q5FUR
                uni.request({
                  url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + lat + ',' + lng + '&key=' + key,
                  method: 'GET',
                  success(ress) {
                    console.log('定位：', ress);
                    let data = ress.data; //获取到所有定位的数据
                    if (data.message) {
                      let adCode = data.result.ad_info.adcode; // adcode: "440305", city: "深圳市" ,city_code: "156440300"
                      let city = data.result.ad_info.city;
                      locationCityName.value = city;
                      // let street = ress.data.result.address_component.street;
                      // cityName.value = street;
                      uni.setStorageSync('CityName', city);
                    }
                  },
                  fail(err) {
                    uni.showToast({
                      title: '获取定位失败: ' + err,
                      icon: 'none'
                    });
                  }
                });
              }
            });
          }
        });
      }
    }
  });
};
</script>

<style lang="scss" scoped>
@import './city.scss';
</style>
